/* cs613011 */

#include <stdio.h>
#include "mpi.h"

int main(int argc, char **argv)
{
	int size, rank;
	MPI_Init(&argc, &argv);

	int returncode = 0;
	
	MPI_Comm old_comm, new_comm;
	int ndims, reorder, ierr, i, j, k;
	int dim_size[2], periods[2];
	int comm_rank;
	int cart_rank;
	int coords[2];

	old_comm = MPI_COMM_WORLD;
	ndims = 2;
	dim_size[0] = 2;
	dim_size[1] = 3;
	periods[0] = 0;
	periods[1] = 0;
	reorder = 0;

	int oldsize = -1;
	int newsize = -1;

	int coordstest_coords[2];
	int coordstest_rank;
	int coordstest_maxdims;

	/*----------------------------------*/
	/* for MPI_Cartdim_get */
	int dimget;
	/* for MPI_Cart_get */
	int getdims[2];
	int getperiods[2];
	int getcoords[2];
	/*----------------------------------*/

	MPI_Comm_rank(MPI_COMM_WORLD, &comm_rank);

	MPI_Comm_size(old_comm, &oldsize);
	printf("%d: Old size: %d\n", comm_rank, oldsize);

	new_comm = 0;
	MPI_Cart_create(old_comm, ndims, dim_size, periods, reorder, &new_comm);
	if (new_comm != MPI_COMM_NULL)
	{			
		MPI_Comm_size(new_comm, &newsize);
		coordstest_maxdims = newsize;

		printf("%d: New size: %d\n", comm_rank, newsize);

		MPI_Cartdim_get(new_comm, &dimget);
		printf("MPI_Cartdim_get shows %d\n", dimget);
		MPI_Cart_get(new_comm, dimget, getdims, getperiods, getcoords);
		
		printf("MPI_Cart_get shows...(%d)(%d),(%d)(%d),[%d][%d].\n", getdims[0], getdims[1],
				getperiods[0], getperiods[1], getcoords[0], getcoords[1]);


		for (i = 0; i < dim_size[0]; i++) {
			for (j = 0; j < dim_size[1]; j++) {
				coords[0] = i;
				coords[1] = j;
				MPI_Cart_rank(new_comm, coords, &cart_rank);
				printf("given coords [%d][%d], rank is %d\n", coords[0], coords[1], cart_rank);
				MPI_Cart_coords(new_comm, cart_rank, 2, coordstest_coords);
				printf("given rank %d, coords are [%d][%d]\n", cart_rank, coordstest_coords[0], coordstest_coords[1]);
				
			}
		}
	}

	MPI_Finalize();
	return 0;
}

